const api = require('../../api/api.js');
const util = require('../../utils/util.js');

Page({
  data: {
    localImgSrc: ''
  },
  onLoad(o) {
    let that = this;
    let siteId = o.siteId;
    let entId = o.entId;
    that.setData({
      siteId,
      entId
    });
  },
  formSubmit(e) {
    let that = this;
    let account = e.detail.value.name.trim();
    let siteId = that.data.siteId;
    let entId = that.data.entId;
    if (account === '') {
      wx.showToast({
        title: '请将填写用户账号！',
        icon: 'none'
      })
      return;
    }
    wx.showLoading({
      title: '绑定中...',
    });
    that.addManager(siteId, entId, account);
  },
  scan() {
    let that = this;
    wx.scanCode({
      success(res) {
        console.log(res);
        let data = JSON.parse(res.result);
        console.log(data);
        let siteId = that.data.siteId;
        let entId = that.data.entId;
        let account = data.account;
        that.addManager(siteId, entId, account, 'scan');
      }
    })
  },
  addManager(siteId, entId, account, scan) {
    let that = this;
    api.addManager({
      data: {
        account,
        siteId,
        entId
      },
      success(res) {
        console.log(res.data);
        let pages = getCurrentPages();
        let prePage = pages[pages.length - 2];
        let state = res.data;
        if (state.type === 0) {
          util.showToast(state.msg, 'none');
          prePage.onLoad({
            siteId,
            entId
          });
          that.formitSuccess(scan);
        } else {
          if (scan !== undefined) {
            prePage.showMsg(state.msg);
          } else {
            util.showToast(state.msg, 'none');
          }
          wx.hideLoading();
        }
      }
    });
  },
  formitSuccess(scan) {
    wx.hideLoading();
    wx.showToast({
      title: '提交成功！',
    });
    if (scan !== undefined) {
      wx.navigateBack({
        delta: '-2'
      });
    } else {
      wx.navigateBack({
        delta: '-1'
      });
    }
  }
})